package com.essc.serviceImpl;

import com.essc.mapper.UserMapper;
import com.essc.pojo.User;
import com.essc.service.UserService;
import com.essc.utils.JsonResult;
import com.essc.utils.Md5Util;
import com.essc.utils.SMSUtil;
import com.essc.utils.VerificationCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.UUID;


@Service
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    UserMapper userMapper;

    public List<User> findAllUserInfo() {
        List<User> userList = userMapper.findAllUser();
        return userList;
    }

    @Override
    public User login(String username, String password) {
        String salt = userMapper.findSaltByUsername(username); //从数据库获取盐值
        String md5Pwd = Md5Util.getMD5Pwd(password,salt); //根据盐值生成加密后的密码
        return userMapper.findUserByUsernameAndPassword(username, md5Pwd); //使用加密后的密码进行登录操作
    }

    /*@Override
    public int register(String username, String password){
        if(username.equals(userMapper.findUsernameByUsername(username))){ //判断数据库是否存在同名用户
            return 0;//如果存在同名，直接返回0，表示插入失败
        }else{ //否则正常注册
            String salt = UUID.randomUUID().toString(); //生成一个盐
            String md5Pwd = Md5Util.getMD5Pwd(password,salt); //利用salt生成md5的密码
            return userMapper.insertUser(username, md5Pwd, salt); //将加密后的密码和salt存入数据库
        }
    }*/
    //注册 洪志成改
    @Override
    public Object register(String username, String password,String tel,
                           String code,HttpServletRequest request) {
        if(username.equals(userMapper.findUsernameByUsername(username))){ //判断数据库是否存在同名用户
            return "error1";//如果存在同名，直接返回error1，表示插入失败
        }else if(tel.equals(userMapper.findTelByTel(tel))){ //判断数据库是否存在同手机号注册
            return "error2";//如果存在同名，直接返回error2，表示插入失败
        }else{ //否则正常注册
            System.out.println("user"+username);
            System.out.println("code"+code);
            System.out.println("code1"+SMSUtil.code1);
            String salt = UUID.randomUUID().toString(); //生成一个盐
            String md5Pwd = Md5Util.getMD5Pwd(password,salt); //利用salt生成md5的密码
            org.json.JSONObject json = (org.json.JSONObject)request.getSession().getAttribute("MsCode"); //校正验证码
            System.out.println(json);
        /*Object code1 = request.getSession().getAttribute("Code");
        System.out.println(code1);*/
            //if(!code1.equals(code)){
        /*System.out.println(("Code"+json.getString("Code")));
        System.out.println(("Code"+json.getString("Code")));*/
       /*if(!json.getString("Code").equals(code)){
            return "验证码错误";
        }*/
            if(!SMSUtil.code1.equals(code)){
                return "验证码错误";
            }
            //我这里模拟了一分钟 超时过期
        /*if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 1){
            return "验证码过期";
        }*/
            if((System.currentTimeMillis() - SMSUtil.time1) > 1000 * 60 * 1){
                return "验证码过期";
            }
            //将用户信息存入数据库
            userMapper.insertUser(username, md5Pwd,tel, salt); //将加密后的密码和salt存入数据库
            //将验证码清空 点击注册后验证码失效
            return "success";
        }
    }


    /**
     * 畅润
     */
//    public JsonResult findUserById(User user1) {
//        if (user1.getUid()==null){
//            return new JsonResult(201,"会话失效，请重新登陆");
//        }
//
//        int uid=user1.getUid();
//        User user = userMapper.findUserById(uid);
//        if (user==null||user.getStatus()==0){
//            return new JsonResult(202,"用户已注销");
//        }
//        System.out.println(user);
//        return new JsonResult(200,"成功查询用户",user);
//    }
    public JsonResult findUserById(int uid) {
        User user = userMapper.findUserById(uid);
        if (user==null||user.getStatus()==0){
            return new JsonResult(202,"用户已注销");
        }
        System.out.println(user);
        return new JsonResult(200,"成功查询用户",user);
    }

    public JsonResult updatePwdById( String oldPwd, String newPwd,Integer uid)
    {
        User user1=userMapper.findUserById(uid);//根据uid查询原密码
        String password=user1.getPassword();//获取原来的密码
        String salt=user1.getSalt();
        System.out.println(salt);
        oldPwd=getMD5Pwd(oldPwd,salt);//将前端传来的旧密码与salt值结合，加密后可与真密码比对
        System.out.println(oldPwd);
        if (!password.equals(oldPwd)){//与前端传来的旧密码，若前端的旧密码填错，则比对失败
            return new JsonResult(201,"原密码填写错误，请重新填写");
        }
        newPwd=getMD5Pwd(newPwd,salt);//原密码输入正确，则对新密码进行加密，然后存储在数据库中
        int row=userMapper.updatePwdById(uid,newPwd);
        if (row!=1){
            return new JsonResult(202,"密码修改失败，请检查格式");
        }
        return new JsonResult(200,"密码修改成功");
    }

    public JsonResult updateUserInfo(User user) {
        int row = userMapper.updateUserInfo(user);
        if (row!=1){
            return new JsonResult(201,"更新数据失败");
        }
        return new JsonResult(200,"更新成功");
    }


    //封装一个方法 对密码进行加密
    private String getMD5Pwd(String password,String salt){
        String md5Pwd=password+salt;
        //加密
        for(int i=0;i<10;i++){
            md5Pwd= DigestUtils.md5DigestAsHex(md5Pwd.getBytes());
        }
        return md5Pwd;
    }

    @Override
    public JsonResult uploadAvatar(MultipartFile file, String username, HttpSession session) throws FileNotFoundException {
        if(file.isEmpty()){
            return new JsonResult(201,"文件找不到");
        }
        String fileName = file.getOriginalFilename(); //原文件名
        //获取文件名后缀
        int index = fileName.lastIndexOf(".");//查询从后往前的第一个.  返回从前往后到这个点的下标
        String suffix = fileName.substring(index);
        //用当前系统时间毫秒值 生成一个新的文件名
        long time=System.currentTimeMillis();
        String newFileName=time+suffix;//新文件名
        //从webapp路径去找upload文件夹，找不到则添加一个名为upload的文件夹
        //String path = session.getServletContext().getRealPath("upload");
        String staticPath = ResourceUtils.getURL("classpath:static").getPath().replace('/', '\\');
        System.out.println(staticPath);
        String path=staticPath+"\\"+"upload";
        System.out.println(path);
        String fullPath=path+"\\"+username;
        File file1=new File(fullPath);
        if (!file1.exists()){
            file1.mkdirs();
        }

        String filePath=fullPath+"\\"+newFileName;
        System.out.println("filepath:"+filePath);
        //使用file2对象描述文件的路径
        File file2=new File(filePath);
        try {
            file.transferTo(file2);
        }
        catch (IOException e) {
            e.printStackTrace();
        }

        String url="http://localhost:8080/upload/"+username+"/"+newFileName;
        session.setAttribute("image",url);
        return new JsonResult(200,"上传成功",url);
    }

    //生成验证码
    @Override
    public String verifyCode( HttpServletResponse resp) throws IOException {
        VerificationCode code = new VerificationCode();
        BufferedImage image = code.getImage();//前端生成图片验证码
        String text = code.getText();//后端生成文本验证码
        VerificationCode.output(image,resp.getOutputStream());//输出前端图片验证码
        return text;
    }

    //充值 洪志成
    @Override
    public JsonResult recharge(Integer uid, double amount) {
        //获取用户原有余额
        User userInfo = userMapper.findUserById(uid);
        Double money = userInfo.getMoney();
        //将数额充值入余额
        Double newmoney = money + amount;
        //更新钱包
        int recharge = userMapper.recharge(uid, newmoney);
        if(recharge!=1){
            return new JsonResult(201,"充值失败",recharge);
        }
        return new JsonResult(200,"充值成功",recharge);
    }

}
